/**
 * 加密工具函数
 * 使用简单的哈希和盐值来加密口令
 */

// 生成随机盐值
function generateSalt(): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let salt = '';
  for (let i = 0; i < 16; i++) {
    salt += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return salt;
}

// 简单的哈希函数（基于字符串）
function simpleHash(str: string): string {
  let hash = 0;
  if (str.length === 0) return hash.toString();

  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash; // Convert to 32-bit integer
  }

  return Math.abs(hash).toString(36);
}

// 使用Web Crypto API进行SHA-256哈希（如果支持）
async function sha256Hash(message: string): Promise<string> {
  if (typeof crypto !== 'undefined' && crypto.subtle) {
    try {
      const msgBuffer = new TextEncoder().encode(message);
      const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
    } catch (error) {
      console.warn('Web Crypto API not available, falling back to simple hash');
      return simpleHash(message);
    }
  }
  return simpleHash(message);
}

/**
 * 加密口令
 * @param password 明文口令
 * @returns 加密后的口令对象，包含哈希值和盐值
 */
export async function encryptPassword(password: string): Promise<{ hash: string; salt: string }> {
  if (!password || password.trim() === '') {
    return { hash: '', salt: '' };
  }

  const salt = generateSalt();
  const saltedPassword = password + salt;
  const hash = await sha256Hash(saltedPassword);

  return { hash, salt };
}

/**
 * 验证口令
 * @param inputPassword 用户输入的明文口令
 * @param storedHash 存储的哈希值
 * @param storedSalt 存储的盐值
 * @returns 是否验证通过
 */
export async function verifyPassword(
  inputPassword: string,
  storedHash: string,
  storedSalt: string
): Promise<boolean> {
  if (!inputPassword || !storedHash || !storedSalt) {
    return false;
  }

  const saltedPassword = inputPassword + storedSalt;
  const hash = await sha256Hash(saltedPassword);

  return hash === storedHash;
}

/**
 * 检查是否设置了口令
 * @param passwordData 口令数据对象
 * @returns 是否设置了口令
 */
export function hasPassword(passwordData: { hash: string; salt: string }): boolean {
  return !!(passwordData?.hash && passwordData?.salt);
}
